package com.dongdongshop.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.TbUserServiceI;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class Realm extends AuthorizingRealm {

    @Reference
    private TbUserServiceI tbUserServiceI;


    /*
    * 执行授权逻辑
    * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        return null;
    }

    /*
    * 执行认证逻辑
    * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;

        TbUser tbUser = tbUserServiceI.getTbUser(token.getUsername());

        // 第一个参数：数据库查询出来的对象，登录成功shiro就会把这个对象放入session中
        // 第二个参数：数据库查询出来的密码，shiro会自动校验
        // 第三个参数：用户名
        if(tbUser == null){
            return null;
        }
        if(!tbUser.getStatus().equals("1")){
            return null;
        }
        return tbUser == null ? null: new SimpleAuthenticationInfo(tbUser,tbUser.getPassword(), ByteSource.Util.bytes(tbUser.getSalt()),tbUser.getUsername());
    }
}
